import React,{Component} from 'react';
import { DatePicker, Menu, Select } from 'antd';
import moment from 'moment';
import 'antd/dist/antd.css';
import styles from '../style.less';

import CameraPlayer from '@/pages/camera/components/CameraPlayer';
import CameraTimeRule from '@/pages/camera/components/CameraTimeRule';
import { connect } from 'umi';
const { Option } = Select;

@connect(({ cameraHistory, loading }) => ({
  cameraHistory,
  loading: loading.models.cameraHistory,
}))
class CameraBack extends Component {
  constructor(props) {
    super(props);
    this.state={
      cameraInfo: {},
      selectDate: null,
      selectRecordTime: null,
    }
    const {
      loading,
      dispatch,
      cameraHistory: { channelList },
    } = props;
    this.selectChannelIndex = -1;
    this.curPlayRecordItem = null;
    this.selectOnChange = this.selectOnChange.bind(this)
    this.handlerPlaybackTime = this.handlerPlaybackTime.bind(this)
    // this.handlerPlayStateChange = this.handlerPlayStateChange(this)
  }
  componentDidMount() {
    if(this.props.selectDate){
      this.setState({
        selectDate: this.props.selectDate
      })
    }

    this.handleQueryChannel();
  }

  componentDidUpdate(prevProps) {
    // 典型用法（不要忘记比较 props）：
    const {cameraHistory: {channelList},selectChannelId } = this.props;
    if (this.selectChannelIndex === -1 && selectChannelId !== undefined) {
      if(channelList.length>0){
        for (let i = 0; i < channelList.length; i++) {
          const channel = channelList[i];
          if(channel.channelId == selectChannelId){
            this.selectChannelIndex = i;
            this.setState({
              cameraInfo: channel
            })
            break;
          }
        }
      }
    }
  }
  handleQueryChannel(){
    const { dispatch } = this.props;
    dispatch({
      type: 'cameraHistory/fetch',
      payload: {},
    })
  }

  handleQueryChannelRecord(cameraInfo,selectDate){
    const { dispatch } = this.props;
    if(cameraInfo && cameraInfo.channelId !== undefined && selectDate !== null){
      dispatch({
        type: 'cameraHistory/channelRecord',
        payload: {
          deviceId: cameraInfo.deviceId,
          channelId: cameraInfo.channelId,
          day: selectDate,
        },
      })
    }
  }

  onChange=(date, dateString)=>{
    this.setState({
      selectDate: dateString,
    })
    this.handleQueryChannelRecord(this.state.cameraInfo,dateString);
  }

  disabledDate(current) {
    return current && current > moment().endOf('day');
  }

  selectOnChange(value){
    const {cameraHistory: {channelList} } = this.props;
    this.selectChannelIndex = value;
    this.setState({
      cameraInfo: channelList[value],
    })
    this.handleQueryChannelRecord(channelList[value],this.state.selectDate);
  }

  getDateSeconds(dateStr){
    const date = new Date(Date.parse(dateStr.replace(/-/g,   "/")))
    return date.getTime();
  }

  getEndDateTime(dateStr){
    const date = new Date(Date.parse(dateStr.replace(/-/g,   "/")))
    const year = date.getFullYear();
    const month =(date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
    const day = date.getDate();
    return `${year}-${month}-${day} 59:59:59`;
  }

  handleTimeRuleSuccess = (value) => {
    const {cameraHistory: {recordList} } = this.props;
    let recordTime = null;
    const selectTime = value;
    const selectSeconds = this.getDateSeconds(selectTime);
    recordList.some((item) => {
      const startSeconds = this.getDateSeconds(item.startTime);
      const endSeconds = this.getDateSeconds(item.endTime);
      if(selectSeconds>=startSeconds && selectSeconds<=endSeconds){
        recordTime={startTime:selectTime,endTime:item.endTime};
        this.curPlayRecordItem = item;// 记录当前的播放文件片段
        return true;
      }
       return false;
    });
    this.setState({
        selectRecordTime: recordTime,
     })
  }

  setStateAsync(state) {
    return new Promise((resolve) => {
      this.setState(state, resolve);
    });
  }

  selectOnSearch(val){

  }

  handlerPlaybackTime(e){
    if(e === 'playbackTime'){ // 更新时间刻度
      this.$timeRule.addTime();
    }else if(e === "ended"){ // 播放结束后，继续播放下一个回放片段
      const {cameraHistory: {recordList} } = this.props;
      if(this.curPlayRecordItem){
        const index = recordList.indexOf(this.curPlayRecordItem);
        if(index>=0 && (index+1)<recordList.length){
          this.curPlayRecordItem = recordList[index+1];
          const recordTime={startTime:this.curPlayRecordItem.startTime,endTime:this.curPlayRecordItem.endTime};
          this.setState({
            selectRecordTime: recordTime,
          })
          this.$timeRule.changeToDateTime(this.curPlayRecordItem.startTime);
        }
      }
    }
  }
  render() {
    const options = {
      width: '100%',
      height: '60px',
      stack: false,
      showMajorLabels: true,
      showCurrentTime: true,
      zoomMin: 1000000,
      type: 'background',
      format: {
        minorLabels: {
          minute: 'h:mma',
          hour: 'ha'
        }
      }
    }
    const {cameraHistory: {channelList,recordList} } = this.props;
    const {cameraInfo,selectRecordTime,selectDate} = this.state;
    const dateFormat = 'YYYY-MM-DD';
    return (
      <div className={styles.camera} >
        <div>
        <div className={styles.cameraList}>
          <div>
            <div className={styles.cameraListTitle0} >选择摄像头</div>
            <div>
              <Select
                showSearch
                style={{ width: 200 }}
                placeholder="请选择摄像头"
                value={this.selectChannelIndex>=0?this.selectChannelIndex:''}
                optionFilterProp="children"
                onChange={this.selectOnChange}
                onSearch={this.selectOnSearch}
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {
                  channelList.map((item, index) => {
                    return <Option value={index} >{item.name}</Option>
                  })
                }
              </Select>
            </div>
          </div>
          <div>
            <div className={styles.cameraListTitle}>选择回放时间</div>
            <DatePicker value={selectDate?moment(selectDate, dateFormat):undefined} format={dateFormat} className={styles.datePicker} disabledDate={this.disabledDate} onChange={this.onChange} />
          </div>
        </div>
        </div>
        <div className={styles.cameraGirdLayout}>
          <div className={styles.cameraBack}>
            <CameraPlayer playbackTime={this.handlerPlaybackTime} liveData={cameraInfo} recordTime={selectRecordTime} history={true}></CameraPlayer>
          </div>
          <div className={styles.cameraBar}>
            <CameraTimeRule onRef={(ref)=> {this.$timeRule=ref}} recordList={recordList} selectDay={selectDate} selectTime={this.handleTimeRuleSuccess}></CameraTimeRule>
          </div>
        </div>
      </div>
    )
  }
}
export default CameraBack;
